package com.sptpc.exam;

import com.sptpc.exam.model.Question;
import com.sptpc.exam.model.User;
import com.sptpc.exam.util.DBHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/admin/usermanage.do")
public class UserManageServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 从数据库读所有账户信息
        Connection conn = null;
        List<User> users = new ArrayList<>();
        try {
            conn = DBHelper.getConnection();
            String sql = "select uid, uname, true_name, major from user";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                User user = new User(rs.getInt("uid"),
                                 rs.getString("uname"),
                                 rs.getString("true_name"),
                                 rs.getString("major"));
                users.add(user);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        request.getSession().setAttribute("users", users);
        request.getRequestDispatcher("userlist.jsp").forward(request, response);
    }
}
